package com.example.pt.service;

import com.example.pt.dto.FavoriteDTO;
import com.example.pt.entity.TorrentFavorite;
import com.example.pt.entity.TorrentFile;
import com.example.pt.entity.User;
import com.example.pt.mapper.TorrentFavoriteMapper;
import com.example.pt.repository.TorrentFileRepository;
import com.example.pt.repository.UserRepositories;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 种子收藏服务
 */
@Service
public class FavoriteService {

    private static final Logger logger = LoggerFactory.getLogger(FavoriteService.class);

    @Autowired
    private TorrentFavoriteMapper torrentFavoriteMapper;
    
    @Autowired
    private TorrentFileRepository torrentFileRepository;
    
    @Autowired
    private UserRepositories userRepositories;
    
    /**
     * 添加收藏
     * @param uid 用户ID
     * @param tid 种子ID
     * @param note 备注
     * @return 是否成功
     */
    @Transactional
    public boolean addFavorite(Integer uid, Integer tid, String note) {
        try {
            // 检查用户是否存在
            Optional<User> userOpt = userRepositories.findById(uid);
            if (!userOpt.isPresent()) {
                logger.warn("添加收藏失败：用户不存在，uid={}", uid);
                return false;
            }
            
            // 检查种子是否存在
            Optional<TorrentFile> torrentOpt = torrentFileRepository.findByTid(tid);
            if (!torrentOpt.isPresent()) {
                logger.warn("添加收藏失败：种子不存在，tid={}", tid);
                return false;
            }
            
            // 检查是否已收藏
            if (torrentFavoriteMapper.checkUserFavorite(uid, tid) > 0) {
                logger.info("种子已被收藏，uid={}, tid={}", uid, tid);
                return true; // 已收藏，视为成功
            }
            
            // 创建收藏记录
            TorrentFavorite favorite = new TorrentFavorite();
            favorite.setUid(uid);
            favorite.setTid(tid);
            favorite.setCreateTime(new Date());
            favorite.setNote(note);
            
            int result = torrentFavoriteMapper.insert(favorite);
            
            if (result > 0) {
                logger.info("收藏种子成功，uid={}, tid={}", uid, tid);
                return true;
            } else {
                logger.warn("收藏种子失败，uid={}, tid={}", uid, tid);
                return false;
            }
        } catch (Exception e) {
            logger.error("添加收藏异常：", e);
            throw e;
        }
    }
    
    /**
     * 取消收藏
     * @param uid 用户ID
     * @param tid 种子ID
     * @return 是否成功
     */
    @Transactional
    public boolean removeFavorite(Integer uid, Integer tid) {
        try {
            int result = torrentFavoriteMapper.removeUserFavorite(uid, tid);
            if (result > 0) {
                logger.info("取消收藏成功，uid={}, tid={}", uid, tid);
                return true;
            } else {
                logger.info("取消收藏失败，可能未收藏，uid={}, tid={}", uid, tid);
                return false;
            }
        } catch (Exception e) {
            logger.error("取消收藏异常：", e);
            throw e;
        }
    }
    
    /**
     * 获取用户收藏列表
     * @param uid 用户ID
     * @return 收藏列表
     */
    public List<FavoriteDTO> getUserFavorites(Integer uid) {
        try {
            return torrentFavoriteMapper.findUserFavorites(uid);
        } catch (Exception e) {
            logger.error("获取用户收藏列表异常：", e);
            throw e;
        }
    }
    
    /**
     * 检查种子是否已收藏
     * @param uid 用户ID
     * @param tid 种子ID
     * @return 是否已收藏
     */
    public boolean isFavorited(Integer uid, Integer tid) {
        try {
            return torrentFavoriteMapper.checkUserFavorite(uid, tid) > 0;
        } catch (Exception e) {
            logger.error("检查收藏状态异常：", e);
            throw e;
        }
    }
} 